<template>
  <div class="immersive-bg position-relative">
    <!-- 半透明遮罩 -->
    <div class="bg-overlay"></div>

    <!-- 主内容 -->
    <div class="container position-relative z-3 py-5" :class="{'disable-overlay': disableInteraction}">
      <h1 class="mb-5 text-center display-3 fw-bold">
        <i class="bi bi-book-fill me-3 text-primary"></i>
        单词背诵 - SuperDe
      </h1>

      <!-- 1. 选择词汇等级或强变化动词 -->
      <div class="row mb-4">
        <div class="col-12">
          <div class="card shadow-lg card-immersive">
            <div class="card-header bg-primary text-white fw-semibold d-flex align-items-center">
              <i class="bi bi-layers-fill me-2"></i>
              <span class="fs-4">选择词汇等级或强变化动词</span>
            </div>
            <div class="card-body">
              <div class="row row-cols-1 row-cols-md-4 g-4">
                <!-- 循环显示每个等级信息 -->
                <div
                  v-for="info in levelsInfo"
                  :key="info.level"
                  class="col d-flex"
                >
                  <div
                    class="card flex-fill shadow-sm border-0 level-card"
                    :class="`level-${info.level}`"
                  >
                    <div class="card-body d-flex flex-column justify-content-center text-center">
                      <h5 class="card-title text-white fw-bold">
                        {{ getLevelLabel(info.level) }}
                      </h5>
                      <p class="card-text mb-1 text-white">总数: {{ info.total_words }}</p>
                      <p class="card-text mb-3 text-white">
                        剩余: {{ info.leftover_words }}
                      </p>
                      <button
                        class="btn btn-light btn-block btn-lg fw-semibold"
                        @click="openStartReciteModal(info.level, false)"
                        :disabled="info.leftover_words === 0 || hasOngoingRecite || hasPendingReviews"
                      >
                        <i class="bi bi-bookmark-plus me-2"></i>
                        开始背诵
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 强变化动词 -->
                <div class="col d-flex">
                  <div class="card flex-fill shadow-sm border-danger level-card level-7">
                    <div class="card-body d-flex flex-column justify-content-center text-center">
                      <h5 class="card-title text-white fw-bold">
                        <i class="bi bi-lightning-fill me-2 text-warning"></i>
                        强变化动词
                      </h5>
                      <p class="card-text mb-1 text-white">
                        总数: {{ starkVerbs.total_words }}
                      </p>
                      <p class="card-text mb-3 text-white">
                        剩余: {{ starkVerbs.leftover_words }}
                      </p>
                      <button
                        class="btn btn-light btn-block btn-lg fw-semibold"
                        @click="openStartReciteModal(null, true)"
                        :disabled="starkVerbs.leftover_words === 0 || hasOngoingRecite || hasPendingReviews"
                      >
                        <i class="bi bi-bookmark-plus me-2"></i>
                        开始背诵
                      </button>
                    </div>
                  </div>
                </div>
                <!-- end row -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 2. 开始复习 -->
      <div class="row mb-4">
        <div class="col-12">
          <div class="card shadow-lg card-immersive">
            <div class="card-header bg-success text-white fw-semibold d-flex align-items-center">
              <i class="bi bi-arrow-repeat me-2"></i>
              <span class="fs-4">复习功能</span>
            </div>
            <div class="card-body">
              <div class="row row-cols-1 row-cols-md-2 g-4">
                <!-- 复习 - 进度复习 -->
                <div class="col d-flex">
                  <div class="card flex-fill shadow-sm border-0 review-card">
                    <div class="card-body d-flex flex-column justify-content-center text-center">
                      <h5 class="card-title text-white fw-bold">
                        <i class="bi bi-calendar-check-fill me-2"></i>
                        进度复习
                      </h5>
                      <p class="card-text mb-1 text-white">需复习: {{ pendingReviewCount }}</p>
                      <button
                        class="btn btn-light btn-block btn-lg fw-semibold"
                        @click="openStartReviewModal('scheduled')"
                        :disabled="pendingReviewCount === 0 || hasOngoingRecite"
                      >
                        <i class="bi bi-arrow-repeat me-2"></i>
                        开始复习
                      </button>
                    </div>
                  </div>
                </div>

                <!-- 复习 - 单词挑战 -->
                <div class="col d-flex">
                  <div class="card flex-fill shadow-sm border-0 review-card">
                    <div class="card-body d-flex flex-column justify-content-center text-center">
                      <h5 class="card-title text-white fw-bold">
                        <i class="bi bi-trophy-fill me-2"></i>
                        单词挑战
                      </h5>
                      <p class="card-text mb-1 text-white">已学习: {{ studiedWordsCount }}</p>
                      <button
                        class="btn btn-light btn-block btn-lg fw-semibold"
                        @click="openStartReviewModal('word_challenge')"
                        :disabled="studiedWordsCount === 0 || hasOngoingRecite"
                      >
                        <i class="bi bi-trophy-fill me-2"></i>
                        开始挑战
                      </button>
                    </div>
                  </div>
                </div>
                <!-- end row -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 3. 提示有正在进行中的背诵或复习 -->
      <div
        v-if="hasOngoingRecite"
        class="alert alert-warning d-flex align-items-center justify-content-between shadow"
      >
        <div class="d-flex align-items-center">
          <i class="bi bi-journal-check me-3 fs-3"></i>
          <span class="fs-5">
            有未完成的背诵或复习任务，可点击下方前往处理~
          </span>
        </div>
        <button class="btn btn-warning btn-lg" @click="openReciteTaskModal">
          <i class="bi bi-arrow-right-circle me-2"></i>
          前往任务
        </button>
      </div>

      <!-- 4. 提示有待复习的单词 -->
      <div
        v-if="hasPendingReviews"
        class="alert alert-info d-flex align-items-center justify-content-between shadow"
      >
        <div class="d-flex align-items-center">
          <i class="bi bi-calendar-check me-3 fs-3"></i>
          <span class="fs-5">
            您有待复习的单词任务，请先完成复习后再开始新的背诵。
          </span>
        </div>
      </div>
    </div>

    <!-- 背诵或复习任务模态框 -->
    <div
      class="modal fade immersive-modal"
      id="reciteTaskModal"
      tabindex="-1"
      aria-labelledby="reciteTaskModalLabel"
      aria-hidden="true"
      ref="reciteTaskModal"
    >
      <div class="modal-dialog modal-super-lg modal-dialog-centered">
        <div class="modal-content frosted-glass text-dark border-0">
          <div class="modal-header border-0">
            <h5 class="modal-title fw-bold" id="reciteTaskModalLabel">
              <i class="bi bi-journal-medical me-2"></i>
              {{ currentSessionTypeLabel }}
              <template v-if="currentTask">
                <span v-if="currentTask.type === 'learn'"> (学习) </span>
                <span v-else-if="currentTask.type === 'test1'">(测试1/多选)</span>
                <span v-else-if="currentTask.type === 'test2'">(测试2/听音填空)</span>
              </template>
            </h5>

          </div>

          <div class="modal-body" :class="{'disable-overlay': disableInteraction}">
            <!-- 完成所有任务 -->
            <div v-if="isCompleted && !isCanceled"  class="text-center p-5">
              <h3 class="fw-bold text-success mb-3">
                <i class="bi bi-check-circle-fill me-2"></i>
                恭喜，你已完成本次 {{ currentSessionTypeLabel }}！
              </h3>
              <p class="fs-5">
                你本次背诵了 {{ reciteRecords.filter(r => r.is_known).length }} 个单词，系统将安排后续复习时间。
              </p>
              <button class="btn btn-success btn-lg mt-4" @click="finallyresetRecite">
                <i class="bi bi-house-fill me-2"></i>
                返回到主页
              </button>
            </div>

            <!-- 学习任务 -->
            <div v-else-if="currentTask.type === 'learn' && currentTask">
              <h5 class="fw-bold mb-4 d-flex align-items-center">
                <i class="bi bi-lightbulb me-2"></i>
                学习阶段 ({{ currentTaskIndex + 1 }}/{{ totalTasks }})
              </h5>

              <!-- 显示词汇类型 -->
              <div class="mb-4 text-center">
                <span class="badge bg-secondary fs-6">{{ currentWord.wordTypeLabel }}</span>
              </div>

              <!-- 词汇展示 -->
              <div class="card bg-white border-0 shadow-sm p-4 mb-4 word-display-box d-flex align-items-center justify-content-between">
                <div>
                  <p class="h3 fw-bold text-primary mb-2">
                    <i class="bi bi-bookmark-heart me-2"></i>
                    {{ currentWord.wordDisplay }}
                  </p>

                  <!-- 词性 badge -->
                  <div class="d-flex justify-content-end">
                    <span class="badge bg-info text-dark me-2">
                      {{ currentWord.wordTypeLabel }}
                    </span>
                    <!-- 显示性别信息（如果是名词） -->
                    <span v-if="currentWord.wordType === '名词' && currentWord.genders.length" class="badge bg-secondary">
                      性别:
                      <span v-for="(gender, idx) in currentWord.genders" :key="idx">
                        {{ genderMap[gender] }}<span v-if="idx < currentWord.genders.length -1">, </span>
                      </span>
                    </span>
                  </div>
                </div>
                <!-- 喇叭图标 -->
                <button class="btn btn-outline-primary" @click="playPronunciation(currentWord.wordDisplay)">
                  <i class="bi bi-volume-up-fill"></i>
                </button>
              </div>

              <div class="card bg-light border-0 shadow-sm p-4 mb-4">
                <h6 class="fw-bold mb-3">
                  <i class="bi bi-info-circle me-2"></i>
                  详细信息
                </h6>
                <p class="mb-2"><strong>释义:</strong> {{ currentWord.chinese }}</p>

                <!-- 例句展示(德文 + 中文翻译) -->
                <p class="mb-2">
                  <strong>例句:</strong>
                </p>
                <ul class="list-group list-group-flush">
                  <li
                    v-for="(sentObj, idx) in currentWord.sentencePairs"
                    :key="idx"
                    class="list-group-item bg-transparent d-flex justify-content-between align-items-center"
                  >
                    <div>
                      <span class="text-primary">德语：{{ sentObj.de }}</span>
                      <br>
                      <span class="text-secondary">中文：{{ sentObj.cn }}</span>
                    </div>
                    <button
                      class="btn btn-outline-primary btn-sm"
                      @click="playPronunciation(sentObj.de)"
                    >
                      <i class="bi bi-volume-up-fill"></i>
                    </button>
                  </li>
                </ul>
              </div>

              <!-- 只有一个“我认识”按钮 -->
              <div class="mt-4 text-center">
                <button
                  class="btn btn-primary btn-lg fw-semibold"
                  @click="completeLearnTask"
                >
                  <i class="bi bi-hand-thumbs-up me-2"></i>
                  学会啦！
                </button>
              </div>
            </div>

            <!-- 测试阶段1：多选释义 -->
            <div v-else-if="currentTask.type === 'test1' && currentWord">
              <h5 class="fw-bold mb-4 d-flex align-items-center">
                <i class="bi bi-chat-square-text-fill me-2"></i>
                测试阶段1：选择正确含义
              </h5>
              <p class="text-secondary mb-4">
                ({{ currentTaskIndex + 1 }}/{{ totalTasks }})
              </p>

              <div class="card bg-white border-0 shadow-sm p-4 mb-4">
                <p class="h3 fw-bold text-primary mb-3">
                  <i class="bi bi-bookmark-check me-2"></i>
                  {{ currentWord.wordDisplay }}
                  <button class="btn btn-outline-secondary btn-sm ms-3" @click="playPronunciation(currentWord.wordDisplay)">
                    <i class="bi bi-volume-up-fill"></i>
                  </button>
                </p>
              </div>

              <p class="fs-5 mb-3">请选择该单词的正确中文翻译：</p>
              <div class="row g-3">
                <div
                  v-for="(option, idx) in currentTestOptions"
                  :key="idx"
                  class="col-12 col-md-6"
                >
                  <div
                    class="card option-card"
                    :class="optionClass(option)"
                    @click="handleChooseOption(option)"
                  >
                    <div class="card-body d-flex align-items-center">
                      <span class="fs-5 fw-semibold text-dark">
                        <strong>{{ optionKeys[idx].toUpperCase() }}.</strong> {{ option }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <div
                v-if="meaningFeedback"
                class="alert mt-4"
                :class="meaningFeedbackClass"
              >
                {{ meaningFeedback }}
              </div>
            </div>

            <!-- 测试阶段2：听音填空 -->
            <div v-else-if="currentTask.type === 'test2' && currentWord">
              <h5 class="fw-bold mb-4 d-flex align-items-center">
                <i class="bi bi-soundwave me-2"></i>
                测试阶段2：听音填空
              </h5>
              <p class="text-secondary mb-4">
                ({{ currentTaskIndex + 1 }}/{{ totalTasks }})
              </p>

              <!-- 展示中文意思和句子的中文意思 -->
              <div class="card bg-secondary text-white shadow-sm p-3 mb-4">
                <p>
                  <strong>中文意思:</strong> {{ currentWord.chinese }}
                  <button class="btn btn-outline-secondary btn-sm ms-3" @click="playPronunciation(currentWord.wordDisplay)">
                    <i class="bi bi-volume-up-fill"></i>
                  </button>
                </p>
                <p><strong>句子中文意思:</strong> {{ currentTask.fillBlankSentenceCn }}</p>
                <!-- 显示性别信息（如果是名词） -->
                <div v-if="currentWord.wordType === '名词' && currentWord.genders.length" class="mt-2">
                  <strong>性别:</strong>
                  <span v-for="(gender, idx) in currentWord.genders" :key="idx">
                    {{ genderMap[gender] }}<span v-if="idx < currentWord.genders.length -1">, </span>
                  </span>
                </div>
              </div>

              <div class="card bg-white border-0 shadow-sm p-4 mb-4">
                <div class="d-flex align-items-center gap-3 mb-3">
                  <button
                    class="btn btn-outline-secondary btn-lg"
                    @click="playPronunciation(currentTask.fillBlankSentenceDe)"
                  >
                    <i class="bi bi-volume-up-fill me-2"></i>
                    播放语音
                  </button>
                  <input
                    type="text"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model="fillBlankInput"
                    placeholder="请输入德语单词原型"
                    @keyup.enter="onEnterTest2"
                    ref="fillBlankInputRef"
                  />
                  <button
                    class="btn btn-info btn-lg rounded-pill"
                    @click="checkFillBlank"
                  >
                    <i class="bi bi-check2-circle me-2"></i>
                    检查
                  </button>
                </div>

                <!-- 提示信息 -->
                <div
                  v-if="fillBlankFeedback"
                  class="alert mt-3"
                  :class="fillBlankFeedbackClass"
                >
                  {{ fillBlankFeedback }}
                </div>
              </div>

              <!-- 增强：如果是强变化动词，添加额外的输入 -->
              <div v-if="currentWord.stark && currentSessionType === 'recitation'" class="card bg-white border-0 shadow-sm p-4 mb-4">
                <h6 class="fw-bold mb-3">
                  <i class="bi bi-gear-fill me-2"></i>
                  强变化动词额外信息
                </h6>

                <!-- 第二分词输入 -->
                <div class="mb-4">
                  <label class="form-label fw-semibold">第二分词 (p2):</label>
                  <input
                    type="text"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model="fillBlankP2"
                    placeholder="请输入第二分词"
                    @keyup.enter="onEnterTest2Stark"
                  />
                  <div
                    v-if="fillBlankP2Feedback"
                    class="alert mt-2"
                    :class="fillBlankP2FeedbackClass"
                  >
                    {{ fillBlankP2Feedback }}
                  </div>
                </div>

                <!-- 现在时第三人称单数输入 -->
                <div class="mb-4">
                  <label class="form-label fw-semibold">现在时第三人称单数 (er/es/sie):</label>
                  <input
                    type="text"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model="fillBlankPresent"
                    placeholder="请输入现在时第三人称单数形式"
                    @keyup.enter="onEnterTest2Stark"
                  />
                  <div
                    v-if="fillBlankPresentFeedback"
                    class="alert mt-2"
                    :class="fillBlankPresentFeedbackClass"
                  >
                    {{ fillBlankPresentFeedback }}
                  </div>
                </div>

                <!-- 过去时第三人称单数输入 -->
                <div class="mb-4">
                  <label class="form-label fw-semibold">过去时第三人称单数 (er/es/sie):</label>
                  <input
                    type="text"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model="fillBlankPast"
                    placeholder="请输入过去时第三人称单数形式"
                    @keyup.enter="onEnterTest2Stark"
                  />
                  <div
                    v-if="fillBlankPastFeedback"
                    class="alert mt-2"
                    :class="fillBlankPastFeedbackClass"
                  >
                    {{ fillBlankPastFeedback }}
                  </div>
                </div>

                <!-- 提交按钮 -->
                <div class="text-end">
                  <button
                    class="btn btn-primary btn-lg fw-semibold rounded-pill"
                    @click="checkFillBlankStark"
                    :disabled="!fillBlankP2 || !fillBlankPresent || !fillBlankPast"
                  >
                    <i class="bi bi-check2-circle me-2"></i>
                    确认
                  </button>
                </div>
              </div>
            </div>

            <!-- 取消和暂停背诵按钮 -->
            <div class="mt-2 text-center" v-if="!isCompleted"> 
              <hr />
              <div class="d-flex justify-content-center gap-4 mt-1">
                <button class="btn btn-warning btn-lg rounded-pill button-container-up" @click="pauseRecite">
                  <i class="bi bi-pause-circle me-2"></i>
                  暂停任务
                </button>
                <button class="btn btn-outline-danger btn-lg rounded-pill button-container-up" @click="confirmCancelRecite">
                  <i class="bi bi-x-circle me-2"></i>
                  取消任务
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 开始背诵模态框：详情框 -->
    <div
      class="modal fade"
      id="startReciteModal"
      tabindex="-1"
      aria-labelledby="startReciteModalLabel"
      aria-hidden="true"
      ref="startReciteModal"
    >
      <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content frosted-glass text-dark border-0">
          <div class="modal-header border-0">
            <h5 class="modal-title fw-bold d-flex align-items-center" id="startReciteModalLabel">
              <i class="bi bi-rocket-takeoff-fill me-2"></i>
              开始背诵
            </h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <!-- 左侧：词汇书简介 -->
              <div class="col-md-6 mb-4">
                <h6 class="fw-semibold mb-3">
                  <i class="bi bi-info-circle-fill me-2"></i>
                  词汇书简介
                </h6>
                <div class="intro-box p-3 bg-light rounded shadow-sm">
                  <p>
                    欢迎使用SuperDe的背诵功能！本词汇书涵盖了德语学习中最常用的词汇，分为不同的等级，帮助您系统地提升德语水平。每个等级精心挑选了适合学习的单词，并配有详细的释义和例句，助您在实际应用中更好地掌握和运用。
                  </p>
                  <p>
                    强变化动词部分特别设计，以帮助您熟悉德语中变化形式较为复杂的动词，确保您在各种语境下都能准确使用。
                  </p>
                  <p>
                    开始背诵后，您将按照学习、测试1和测试2的阶段进行单词的记忆和复习，每个阶段都有明确的目标和反馈，确保您的学习效果。
                  </p>
                </div>
              </div>

              <!-- 右侧：背诵进度与选择 -->
              <div class="col-md-6">
                <h6 class="fw-semibold mb-3 d-flex align-items-center">
                  <i class="bi bi-bar-chart-fill me-2"></i>
                  背诵进度
                </h6>
                <div class="progress-section mb-4">
                  <p class="mb-1">进度：</p>
                  <div class="progress" style="height: 25px;">
                    <div
                      class="progress-bar progress-bar-striped progress-bar-animated"
                      role="progressbar"
                      :style="{ width: progressPercentage + '%' }"
                      :aria-valuenow="progressPercentage"
                      aria-valuemin="0"
                      aria-valuemax="100"
                    >
                      {{ progressPercentage.toFixed(1) }}%
                    </div>
                  </div>
                  <p class="mt-2">已背诵 {{ recitedCount }} / {{ totalWords }} 个单词</p>
                </div>

                <div class="selection-section mb-4">
                  <label class="fw-semibold fs-5">请选择要背诵的单词数量：</label>
                  <input
                    type="number"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model.number="reciteCount"
                    min="5"
                    :max="maxReciteCount"
                  />
                  <p class="small text-muted mt-2">
                    将从当前选择的范围中随机抽取 {{ reciteCount }} 个单词，开始背诵。
                  </p>
                </div>

                <div class="instructions-section mb-4">
                  <h6 class="fw-semibold">快捷键操作说明：</h6>
                  <ul class="small">
                    <li>在学习阶段：按 <strong>Enter</strong> 键表示“我认识/继续”。</li>
                    <li>在测试1阶段：按 <strong>A</strong>、<strong>B</strong>、<strong>C</strong>、<strong>D</strong> 键选择对应选项。</li>
                    <li>在测试2阶段：按 <strong>Enter</strong> 键提交答案。</li>
                    <li>按 <strong>]</strong> 键播放当前单词的发音。</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer border-0">
            <button
              type="button"
              class="btn btn-secondary btn-lg rounded-pill"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary btn-lg fw-semibold rounded-pill"
              @click="startRecite"
              :disabled="reciteCount < 5 || reciteCount > maxReciteCount"
            >
              <i class="bi bi-play-circle me-2"></i>
              开始
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 开始复习模态框 -->
    <div
      class="modal fade"
      id="startReviewModal"
      tabindex="-1"
      aria-labelledby="startReviewModalLabel"
      aria-hidden="true"
      ref="startReviewModal"
    >
      <div class="modal-dialog modal-dialog-centered modal-xl">
        <div class="modal-content frosted-glass text-dark border-0">
          <div class="modal-header border-0">
            <h5 class="modal-title fw-bold d-flex align-items-center" id="startReviewModalLabel">
              <i class="bi bi-rocket-takeoff-fill me-2"></i>
              开始复习
            </h5>
            <button
              type="button"
              class="btn-close"
              data-bs-dismiss="modal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <div class="row">
              <!-- 左侧：复习简介 -->
              <div class="col-md-6 mb-4">
                <h6 class="fw-semibold mb-3">
                  <i class="bi bi-info-circle-fill me-2"></i>
                  复习功能简介
                </h6>
                <div class="intro-box p-3 bg-light rounded shadow-sm">
                  <p>
                    欢迎使用SuperDe的复习功能！您可以选择按照进度复习，系统将自动安排您需要复习的单词，确保您的记忆得以巩固。
                  </p>
                  <p>
                    或者选择单词挑战，从已学习的单词中随机抽取，进一步提升您的记忆力和应对能力。
                  </p>
                  <p>
                    请根据您的需求选择合适的复习模式，开始您的德语学习之旅！
                  </p>
                </div>
              </div>

              <!-- 右侧：复习进度与选择 -->
              <div class="col-md-6">
                <h6 class="fw-semibold mb-3 d-flex align-items-center">
                  <i class="bi bi-bar-chart-fill me-2"></i>
                  复习进度
                </h6>
                <div class="progress-section mb-4">
                  <p class="mb-1">进度：</p>
                  <div class="progress" style="height: 25px;">
                    <div
                      class="progress-bar progress-bar-striped progress-bar-animated"
                      role="progressbar"
                      :style="{ width: reviewProgressPercentage + '%' }"
                      :aria-valuenow="reviewProgressPercentage"
                      aria-valuemin="0"
                      aria-valuemax="100"
                    >
                      {{ reviewProgressPercentage.toFixed(1) }}%
                    </div>
                  </div>
                  <p class="mt-2">已复习 {{ reviewRecitedCount }} / {{ reviewTotalWords }} 个单词</p>
                </div>

                <div class="selection-section mb-4">
                  <label class="fw-semibold fs-5">请选择要复习的单词数量：</label>
                  <input
                    type="number"
                    class="form-control form-control-lg rounded-pill immersive-input"
                    v-model.number="reviewCount"
                    min="5"
                    :max="maxReviewCount"
                  />
                  <p class="small text-muted mt-2">
                    将从待复习的单词中随机抽取 {{ reviewCount }} 个单词，开始复习。
                  </p>
                </div>

                <div class="instructions-section mb-4">
                  <h6 class="fw-semibold">快捷键操作说明：</h6>
                  <ul class="small">
                    <li>在学习阶段：按 <strong>Enter</strong> 键表示“我认识/继续”。</li>
                    <li>在测试1阶段：按 <strong>A</strong>、<strong>B</strong>、<strong>C</strong>、<strong>D</strong> 键选择对应选项。</li>
                    <li>在测试2阶段：按 <strong>Enter</strong> 键提交答案。</li>
                    <li>按 <strong>P</strong> 键播放当前单词的发音。</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer border-0">
            <button
              type="button"
              class="btn btn-secondary btn-lg rounded-pill"
              data-bs-dismiss="modal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary btn-lg fw-semibold rounded-pill"
              @click="startReview"
              :disabled="reviewCount < 5"
            >
              <i class="bi bi-play-circle me-2"></i>
              开始
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 取消确认模态框 -->
    <div
      class="modal fade"
      id="confirmCancelModal"
      tabindex="-1"
      aria-labelledby="confirmCancelModalLabel"
      aria-hidden="true"
      ref="confirmCancelModal"
    >
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content frosted-glass text-dark border-0">
          <div class="modal-header border-0">
            <h5 class="modal-title fw-bold" id="confirmCancelModalLabel">
              <i class="bi bi-exclamation-triangle-fill me-2 text-warning"></i>
              确认取消任务
            </h5>
            <button
              type="button"
              class="btn-close"
              @click="closeConfirmCancelModal"
              aria-label="Close"
            ></button>
          </div>
          <div class="modal-body">
            <p>取消任务将无法保留当前的进度，您确定要取消吗？</p>
          </div>
          <div class="modal-footer border-0">
            <button
              type="button"
              class="btn btn-secondary btn-lg rounded-pill"
              @click="closeConfirmCancelModal"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-danger btn-lg fw-semibold rounded-pill"
              @click="cancelRecite"
            >
              确认取消
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch, onBeforeUnmount, nextTick } from "vue";
import axios from "axios";
import correctSound from '@/assets/sounds/correct.mp3';
import incorrectSound from '@/assets/sounds/incorrect.mp3';

export default {
  name: "RecitePage",
  setup() {
    // =============== 1. 基础设置 ===============
    const BASE_URL = "http://localhost:8080/api/recite";

    const getToken = () => localStorage.getItem("accessToken") || "";

    const levelsInfo = ref([]);
    const starkVerbs = ref({ total_words: 0, leftover_words: 0 });
    const currentSessionId = ref(null);
    const startReciteModal = ref(null);
    const startReviewModal = ref(null);
    const reciteTaskModal = ref(null);
    const confirmCancelModal = ref(null);
    const fillBlankInputRef = ref(null);
    const isCanceled = ref(false); 

    let all_data = ref(null);

    let bootstrapStartReciteModalInstance = null;
    let bootstrapStartReviewModalInstance = null;
    let bootstrapTaskModalInstance = null;
    let bootstrapConfirmCancelModalInstance = null;

    const selectedLevel = ref(null);
    const selectedIsStark = ref(false);

    const reciteCount = ref(5); 
    const maxReciteCount = computed(() => {
      if (selectedIsStark.value) {
        return Math.min(starkVerbs.value.leftover_words, 50);
      }
      const levelInfo = levelsInfo.value.find(
        (info) => info.level === selectedLevel.value
      );
      return levelInfo ? Math.min(levelInfo.leftover_words, 50) : 50;
    });

    // 复习数据
    const reviewCount = ref(5);
    const maxReviewCount = computed(() => {
      return Math.min(pendingReviewCount.value, 50);
    });
    const pendingReviewCount = ref(0);
    const studiedWordsCount = ref(0);

    // 性别映射
    const genderMap = {
      n: "中性",
      m: "阳性",
      f: "阴性",
    };

    // =============== 2. 任务队列相关 ===============
    let taskQueue = ref([]);
    const currentTaskIndex = ref(0);
    const currentTask = ref({'type': 0});

    const reciteRecords = ref([]);

    let totalTasks = ref(0);
    const isCompleted = ref(false);

    const currentSessionType = ref('recitation'); 
    
    // **新增：在回答后禁用交互**
    const disableInteraction = ref(false);

    // =============== 3. 学习阶段数据与操作 ===============
    const completeLearnTask = async () => {

      const wordId = currentTask.value.wordId;
      try {
        // 更新 stage 为 2（测试1）
        await axios.post(
          `${BASE_URL}/update-record/`,
          { record_id: wordId, stage: 2 },
          { headers: { Authorization: `Bearer ${getToken()}` } }
        );

        // 添加测试1任务
        taskQueue.value.push({ type: "test1", wordId });
        totalTasks.value ++;
        proceedToNextTask();
      } catch (err) {
        console.error("更新学习记录失败:", err);
      }
    };

    // =============== 4. 测试阶段数据与操作 ===============
    const selectedOption = ref(null);
    const meaningFeedback = ref("");
    const meaningFeedbackClass = ref("");
    const canProceed = ref(false);

    const optionKeys = ['A', 'B', 'C', 'D'];

    // **将点击选项与判断逻辑拆分，方便统一处理禁用交互**
    const handleChooseOption = (option) => {
      if (disableInteraction.value) return; // 禁用交互时，不处理点击
      selectedOption.value = option;
      checkMeaningChoice(option);
    };

    const checkMeaningChoice = async (option) => {
      if (disableInteraction.value) return;
      disableInteraction.value = true; // 禁用交互，直到下一题

      const wordObj = getCurrentWord();
      const correctTranslation = wordObj.chinese || "";
      const correct = option === correctTranslation;

      try {
        if (correct) {
          // 更新 stage 为 3（测试2）
          await axios.post(
            `${BASE_URL}/update-record/`,
            { record_id: wordObj.id, stage: 3 },
            { headers: { Authorization: `Bearer ${getToken()}` } }
          );
          // 添加测试2任务
          taskQueue.value.push({ type: "test2", wordId: wordObj.id });
          totalTasks.value ++;
          meaningFeedback.value = "回答正确！";
          meaningFeedbackClass.value = "alert-success";
          playSound('correct');
        } else {
          // 答错了 -> 重新添加学习任务
          await axios.post(
            `${BASE_URL}/update-record/`,
            { record_id: wordObj.id, stage: 1 },
            { headers: { Authorization: `Bearer ${getToken()}` } }
          );
          taskQueue.value.push({ type: "learn", wordId: wordObj.id });
          totalTasks.value ++;
          meaningFeedback.value = `错误，正确答案：${correctTranslation}`;
          meaningFeedbackClass.value = "alert-danger";
          playSound('incorrect');
        }

        // 1.5s 后进入下一个任务
        setTimeout(() => {
          proceedToNextTask();
          disableInteraction.value = false; // 恢复交互
        }, 1500);

      } catch (err) {
        console.error("更新测试1记录失败:", err);
        disableInteraction.value = false;
      }
    };

    const fillBlankInput = ref("");
    const fillBlankFeedback = ref("");
    const fillBlankFeedbackClass = ref("");

    // 强变化动词额外输入
    const fillBlankP2 = ref("");
    const fillBlankP2Feedback = ref("");
    const fillBlankP2FeedbackClass = ref("");

    const fillBlankPresent = ref("");
    const fillBlankPresentFeedback = ref("");
    const fillBlankPresentFeedbackClass = ref("");

    const fillBlankPast = ref("");
    const fillBlankPastFeedback = ref("");
    const fillBlankPastFeedbackClass = ref("");

    // 在测试2按回车时
    const onEnterTest2 = () => {
      if (disableInteraction.value) return;
      checkFillBlank();
    };
    const onEnterTest2Stark = () => {
      if (disableInteraction.value) return;
      checkFillBlankStark();
    };

    const checkFillBlank = async () => {
      if (disableInteraction.value) return;
      disableInteraction.value = true;

      if (!fillBlankInput.value.trim()) {
        fillBlankFeedback.value = "请输入一个单词。";
        fillBlankFeedbackClass.value = "alert-danger";
        disableInteraction.value = false;
        return;
      }

      const wordObj = getCurrentWord();
      let target = wordObj.wordType === "名词" && wordObj.baseForm ? wordObj.baseForm : wordObj.wordDisplay;

      if (fillBlankInput.value.trim().toLowerCase() === target.toLowerCase()) {
        fillBlankFeedback.value = "回答正确！";
        fillBlankFeedbackClass.value = "alert-success";
        playSound('correct');

        // 标记单词为已完成(stage=4)
        try {
          await axios.post(
            `${BASE_URL}/update-record/`,
            { record_id: wordObj.id, is_known: true, stage: 4 },
            { headers: { Authorization: `Bearer ${getToken()}` } }
          );
        } catch (err) {
          console.error("更新测试2记录失败:", err);
        }
      } else {
        fillBlankFeedback.value = `回答错误，正确答案是：${target}`;
        fillBlankFeedbackClass.value = "alert-danger";
        playSound('incorrect');

        // 答错了 -> 重新添加学习任务
        try {
          await axios.post(
            `${BASE_URL}/update-record/`,
            { record_id: wordObj.id, stage: 1 },
            { headers: { Authorization: `Bearer ${getToken()}` } }
          );
          taskQueue.value.push({ type: "learn", wordId: wordObj.id });
        } catch (err) {
          console.error("更新测试2记录失败:", err);
        }
      }

      // 1.5s后进入下一个任务
      setTimeout(() => {
        proceedToNextTask();
        disableInteraction.value = false;
      }, 1500);
    };

    // 检查第二分词
    const checkFillBlankP2 = async () => {
      if (!fillBlankP2.value.trim()) {
        fillBlankP2Feedback.value = "请输入第二分词。";
        fillBlankP2FeedbackClass.value = "alert-danger";
        return false;
      }
      const wordObj = getCurrentWord();
      const correctP2 = wordObj.p2 || "";

      if (
        fillBlankP2.value.trim().toLowerCase() === correctP2.toLowerCase()
      ) {
        fillBlankP2Feedback.value = "第二分词正确！";
        fillBlankP2FeedbackClass.value = "alert-success";
        return true;
      } else {
        fillBlankP2Feedback.value = `错误，正确答案是：${correctP2}`;
        fillBlankP2FeedbackClass.value = "alert-danger";
        return false;
      }
    };

    // 检查现在时第三人称
    const checkFillBlankPresent = async () => {
      if (!fillBlankPresent.value.trim()) {
        fillBlankPresentFeedback.value = "请输入现在时第三人称单数形式。";
        fillBlankPresentFeedbackClass.value = "alert-danger";
        return false;
      }
      const wordObj = getCurrentWord();
      const presentConj = wordObj.a3 || "";

      if (
        fillBlankPresent.value.trim().toLowerCase() === presentConj.toLowerCase()
      ) {
        fillBlankPresentFeedback.value = "现在时第三人称单数形式正确！";
        fillBlankPresentFeedbackClass.value = "alert-success";
        return true;
      } else {
        fillBlankPresentFeedback.value = `错误，正确答案是：${presentConj}`;
        fillBlankPresentFeedbackClass.value = "alert-danger";
        return false;
      }
    };

    // 检查过去时第三人称
    const checkFillBlankPast = async () => {
      if (!fillBlankPast.value.trim()) {
        fillBlankPastFeedback.value = "请输入过去时第三人称单数形式。";
        fillBlankPastFeedbackClass.value = "alert-danger";
        return false;
      }
      const wordObj = getCurrentWord();
      const pastConj = wordObj.b3 || "";

      if (
        fillBlankPast.value.trim().toLowerCase() === pastConj.toLowerCase()
      ) {
        fillBlankPastFeedback.value = "过去时第三人称单数形式正确！";
        fillBlankPastFeedbackClass.value = "alert-success";
        return true;
      } else {
        fillBlankPastFeedback.value = `错误，正确答案是：${pastConj}`;
        fillBlankPastFeedbackClass.value = "alert-danger";
        return false;
      }
    };

    const checkFillBlankStark = async () => {
      if (disableInteraction.value) return;
      disableInteraction.value = true;

      // 检查必填原型
      if (!fillBlankInput.value.trim()) {
        fillBlankFeedback.value = "请先填写动词原型。";
        fillBlankFeedbackClass.value = "alert-danger";
        disableInteraction.value = false;
        return;
      }

      // 先检查普通原型
      await checkFillBlank(); 
      // 注意：checkFillBlank 内部会 setTimeout 切换到下一题，我们需要阻断或合并
      // 这里做一个特殊处理：如果已经 proceedToNextTask 就跳出
      // 简化做法：把强变化动词的检查和普通原型拆开。此处可以做更复杂的逻辑来合并，但为了演示逻辑，示例如下

      // 如果还没 proceedToNextTask，就继续检查 p2, present, past
      const p2Valid = await checkFillBlankP2();
      const presentValid = await checkFillBlankPresent();
      const pastValid = await checkFillBlankPast();

      // 如果三个都对，可以再进行一次 stage 更新(可自行扩展逻辑)
      if (p2Valid && presentValid && pastValid) {
        playSound('correct');
      }
      // 不管对错，都在 checkFillBlank 里的 setTimeout 里 proceedToNextTask 了
      // 所以此处我们就不再额外 proceed

      setTimeout(() => {
        disableInteraction.value = false;
      }, 1500);
    };

    // =============== 5. 解析后端数据 ===============
    const parseWordData = (rawObj) => {
      let type = '';
      if (rawObj.word_type === "N") {
        type = '名词';
      } else if (rawObj.word_type === "V") {
        type = '动词';
      } else if (rawObj.word_type === "A") {
        type = '形容词';
      } else {
        type = '其他';
      }

      // 原始句子数组
      const senArr = Array.isArray(rawObj.sentences) 
        ? rawObj.sentences 
        : (rawObj.sentences || "").split("#");
      const cnArr = Array.isArray(rawObj.chinese_sentences)
        ? rawObj.chinese_sentences
        : (rawObj.chinese_sentences || "").split("#");

      const pairs = senArr.map((s, idx) => ({
        de: s.trim(),
        cn: cnArr[idx] ? cnArr[idx].trim() : "",
      }));

      let record = {
        id: rawObj.id || null, 
        wordType: type,
        wordTypeLabel: getLevelLabelByType(type),
        wordDisplay: rawObj.word || "",
        chinese: rawObj.chinese || "",
        sentencePairs: pairs,
        baseForm: rawObj.baseForm || "",
        genders: rawObj.gender || [], 
        p2: rawObj.p2 || "",
        a3: rawObj.a3 || "",
        b3: rawObj.b3 || "",
        sessionId: rawObj.session || null,
        stark: rawObj.stark || false,
      };

      return record;
    };

    // =============== 6. 获取/提交数据接口 ===============
    const fetchLevelsInfo = async () => {
      try {
        const resp = await axios.get(`${BASE_URL}/levels-info/`, {
          headers: { Authorization: `Bearer ${getToken()}` },
        });
        levelsInfo.value = resp.data.levels_info || [];
        starkVerbs.value =
          resp.data.stark_verbs || { total_words: 0, leftover_words: 0 };
      } catch (error) {
        console.error("获取 levels-info 失败:", error);
      }
    };

    const fetchReviewStats = async () => {
      try {
        const resp1 = await axios.get(`${BASE_URL}/review/words/scheduled/`, {
          headers: { Authorization: `Bearer ${getToken()}` },
        });
        pendingReviewCount.value = resp1.data.length;

        const resp2 = await axios.get(`${BASE_URL}/review/words/all/`, {
          headers: { Authorization: `Bearer ${getToken()}` },
        });
        studiedWordsCount.value = resp2.data.length;
      } catch (error) {
        console.error("获取复习统计信息失败:", error);
      }
    };

    const openStartReciteModal = (level, isStark) => {
      if (hasPendingReviews.value) {
        alert("您有待复习的任务，请先完成复习后再开始背诵。");
        return;
      }
      selectedLevel.value = level;
      selectedIsStark.value = isStark;
      reciteCount.value = 5; 
      bootstrapStartReciteModalInstance && bootstrapStartReciteModalInstance.show();
    };

    const openStartReviewModal = (reviewType) => {
      if (hasOngoingRecite.value) {
        alert("您有正在进行的背诵或复习任务，请先完成或取消后再开始新的复习。");
        return;
      }
      currentReviewType.value = reviewType;
      reviewCount.value = 5;
      bootstrapStartReviewModalInstance && bootstrapStartReviewModalInstance.show();
    };

    const currentReviewType = ref('scheduled');

    const startRecite = async () => {
      try {
        const payload = {
          count: reciteCount.value,
          is_stark: selectedIsStark.value,
        };
        if (!selectedIsStark.value) {
          payload.level = selectedLevel.value;
        }

        const resp = await axios.post(`${BASE_URL}/start/`, payload, {
          headers: { Authorization: `Bearer ${getToken()}` },
        });

        currentSessionId.value = resp.data.session.id;
        all_data.value = resp.data;
        if (!resp.data.records) {
          alert("后端尚未返回 records 数据。");
          return;
        }

        reciteRecords.value = resp.data.records.map((item) =>
          parseWordData(item)
        );

        // 为每个单词添加一个“学习”任务
        taskQueue.value = reciteRecords.value.map((rec) => ({
          type: "learn",
          wordId: rec.id,
        }));

        currentSessionType.value = 'recitation'; 
        
        currentTaskIndex.value = 0;
        currentTask.value = taskQueue.value[0] || null;
        totalTasks.value = taskQueue.value.length;
        persistProgress();

        bootstrapStartReciteModalInstance.hide();
        openReciteTaskModal();
      } catch (err) {
        console.error("开始背诵失败:", err);
        alert("开始背诵失败，请查看控制台或网络请求。");
      }
    };

    const startReview = async () => {
      try {
        const payload = {
          review_type: currentReviewType.value,
          count: reviewCount.value,
        };

        const resp = await axios.post(`${BASE_URL}/start-review/`, payload, {
          headers: { Authorization: `Bearer ${getToken()}` },
        });
        if (!resp.data.records) {
          alert("后端尚未返回 records 数据。");
          return;
        }
        currentSessionId.value = resp.data.session.id;
        all_data.value = resp.data;
        reciteRecords.value = resp.data.records.map((item) =>
          parseWordData(item)
        );

        taskQueue.value = reciteRecords.value.map((rec) => ({
          type: "learn",
          wordId: rec.id,
        }));

        currentSessionType.value = 
          payload.review_type === 'scheduled' ? 'scheduled_review' : 'word_challenge';

        currentTaskIndex.value = 0;
        currentTask.value = taskQueue.value[0] || null;

        persistProgress();

        bootstrapStartReviewModalInstance.hide();
        openReciteTaskModal();
      } catch (err) {
        console.error("开始复习失败:", err);
        alert("开始复习失败，请查看控制台或网络请求。");
      }
    };

    const openReciteTaskModal = () => {
      bootstrapTaskModalInstance && bootstrapTaskModalInstance.show();
      nextTick(() => {
        if (currentTask.value && currentTask.value.type === "test2") {
          fillBlankInputRef.value && fillBlankInputRef.value.focus();
        }
      });
    };

    const confirmCancelRecite = () => {
      bootstrapConfirmCancelModalInstance.show();
    };

    const closeConfirmCancelModal = () => {
      bootstrapConfirmCancelModalInstance.hide();
    };

    const cancelRecite = async () => {
      if (!currentSessionId.value) {
        alert("当前没有进行中的任务。");
        return;
      }

      try {
        await axios.post(
          `${BASE_URL}/cancel/`,
          { session_id: currentSessionId.value },
          { headers: { Authorization: `Bearer ${getToken()}` } }
        );
        isCanceled.value = true;

        // **需求1：直接刷新页面**
        window.location.reload();

      } catch (err) {
        console.error("取消背诵失败:", err);
        alert("取消背诵失败，请查看控制台或网络请求。");
      } finally {
        bootstrapTaskModalInstance && bootstrapTaskModalInstance.hide();
      }
    };
    
    function shuffleArray(array) {
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
    }

    // =============== 7. 任务流转 ===============
    const proceedToNextTask = async () => {
      currentTaskIndex.value++;

      taskQueue.value.shift();

      // 更新当前任务为数组中的第一个元素
      if (taskQueue.value.length > 0) {
        shuffleArray(taskQueue.value);
        currentTask.value = taskQueue.value[0];
        prepareCurrentTask();
      } else {
        // 处理任务队列为空的情况
        isCompleted.value = true;
        await endCurrentSession();
      }
    };

    const prepareCurrentTask = async () => {
        meaningFeedback.value = "";
        meaningFeedbackClass.value = "";
        selectedOption.value = null;

        fillBlankInput.value = "";
        fillBlankFeedback.value = "";
        fillBlankFeedbackClass.value = "";

        fillBlankP2.value = "";
        fillBlankP2Feedback.value = "";
        fillBlankP2FeedbackClass.value = "";

        fillBlankPresent.value = "";
        fillBlankPresentFeedback.value = "";
        fillBlankPresentFeedbackClass.value = "";

        fillBlankPast.value = "";
        fillBlankPastFeedback.value = "";
        fillBlankPastFeedbackClass.value = "";

        if (!currentTask.value) return;

        if (currentTask.value.type === "test1") {
            const w = getCurrentWord();
            const correctTranslation = w.chinese || "（无翻译）";
            currentTestOptions.value = generateTestOptions(correctTranslation);
        } else if (currentTask.value.type === "test2") {
            const w = getCurrentWord();
            const pairs = w.sentencePairs || [];
            if (pairs.length > 0) {
                const randomIndex = Math.floor(Math.random() * pairs.length);
                currentTask.value.fillBlankSentenceDe = pairs[randomIndex].de || "";
                currentTask.value.fillBlankSentenceCn = pairs[randomIndex].cn || "";
            } else {
                currentTask.value.fillBlankSentenceDe = w.wordDisplay || "";
                currentTask.value.fillBlankSentenceCn = "（暂无翻译）";
            }

            await nextTick();
            fillBlankInputRef.value && fillBlankInputRef.value.focus();
        }
    };


    const endCurrentSession = async () => {
      try {
        await axios.post(
          `${BASE_URL}/end-session/`,
          { session_id: currentSessionId.value },
          { headers: { Authorization: `Bearer ${getToken()}` } }
        );
      } catch (err) {
        console.error("结束会话失败:", err);
      }
    };

    // =============== 8. 辅助函数 ===============
    const getCurrentWord = () => {
      if (!currentTask.value) return null;
      return reciteRecords.value.find(
        (r) => r.id === currentTask.value.wordId
      );
    };

    const currentWord = computed(() => {
      return getCurrentWord() || {};
    });

    const currentTestOptions = ref([]);
    const generateTestOptions = (correct) => {
      const options = [correct];
      const otherCandidates = reciteRecords.value
        .map((r) => r.chinese)
        .filter((tr) => tr && tr !== correct);

      shuffleArray(otherCandidates);
      const errorOpts = otherCandidates.slice(0, 3);
      options.push(...errorOpts);
      shuffleArray(options);
      return options;
    };



    // 播放发音
    const playPronunciation = async (text) => {
      if (!text) return;
      try {
        const encoded = encodeURIComponent(text);
        const resp = await axios.get(`/api/pronunciation/${encoded}/`, {
          headers: { Authorization: `Bearer ${getToken()}` },
          responseType: "blob",
        });
        const audioUrl = URL.createObjectURL(resp.data);
        if (!audioUrl) {
          alert("未获取到发音地址");
          return;
        }
        const audio = new Audio(audioUrl);
        audio.play();
      } catch (err) {
        console.error("播放发音失败:", err);
        alert("播放发音失败，请查看控制台或网络请求。");
      }
    };

    // =============== 10. 进度存储与恢复 ===============
    const persistProgress = () => {
      // 如果需要，也可以存在 localStorage；但主要是要与后端数据保持一致
      // 这里按需保留
    };

    const restoreProgress = async () => {
        try {
            const resp = await axios.get(`${BASE_URL}/ongoing-sessions/`, {
                headers: { Authorization: `Bearer ${getToken()}` },
            });

            if (resp.data.ongoing_sessions.length > 0) {
                const session = resp.data.ongoing_sessions[0];
                currentSessionId.value = session.id;
                currentSessionType.value = session.session_type;
                hasOngoingRecite.value = true;

                // 检查任务是否已完成
                if (session.records.every((r) => r.stage >= 4)) {
                    await endCurrentSession(); // 如果所有任务已完成，结束当前会话
                    return;
                }

                // 恢复任务队列
                taskQueue.value = session.records
                    .filter((r) => r.stage < 4)
                    .map((record) => ({
                        type: getTaskTypeByStage(record.stage),
                        wordId: record.id,
                    }));

                // 恢复单词记录
                reciteRecords.value = session.records.map((record) =>
                    parseWordData(record)
                );

                // 恢复当前任务
                currentTaskIndex.value = 0;
                currentTask.value = taskQueue.value[0] || null;
                totalTasks.value = taskQueue.value.length;

                // 准备第一个任务
                prepareCurrentTask();
            }
        } catch (err) {
            console.error("获取未完成任务失败:", err);
        }
    };


    const getTaskTypeByStage = (stage) => {
        switch (stage) {
            case 1:
                return "learn";
            case 2:
                return "test1";
            case 3:
                return "test2";
            default:
                return null;
        }
    };

    const resetRecite = () => {
      taskQueue.value = [];
      currentTaskIndex.value = 0;
      currentTask.value = null;
      reciteRecords.value = [];
      currentSessionId.value = null;
      currentSessionType.value = 'recitation';
      isCanceled.value = false;
      isCompleted.value = false;
      fetchLevelsInfo();
      fetchReviewStats();
    };

    const finallyresetRecite = () => {
      endCurrentSession();
      resetRecite();

      bootstrapTaskModalInstance && bootstrapTaskModalInstance.hide();
      bootstrapConfirmCancelModalInstance && bootstrapConfirmCancelModalInstance.hide();
    };

    const hasOngoingRecite = ref(false);

    const hasPendingReviews = computed(() => {
      return pendingReviewCount.value > 0;
    });

    // =============== 11. 键盘事件处理 ===============
    const handleKeyDown = (event) => {
      if (disableInteraction.value) return; // 如果已禁用交互，则不处理任何键盘事件
      if (!hasOngoingRecite.value) return;
      if (!currentTask.value) return;

      if (currentTask.value.type === "learn") {
        if (event.key === "Enter") {
          event.preventDefault();
          completeLearnTask();
        }
        if (event.key.toLowerCase() === ']') {
          event.preventDefault();
          playPronunciation(currentWord.value.wordDisplay);
        }
      }

      if (currentTask.value.type === "test1") {
        const key = event.key.toUpperCase();
        const index = optionKeys.indexOf(key);
        if (index !== -1 && currentTestOptions.value[index]) {
          event.preventDefault();
          handleChooseOption(currentTestOptions.value[index]);
        }
        if (event.key.toLowerCase() === ']') {
          event.preventDefault();
          playPronunciation(currentWord.value.wordDisplay);
        }
      }

      if (currentTask.value.type === "test2") {
        if (event.key.toLowerCase() === ']') {
          event.preventDefault();
          playPronunciation(currentWord.value.wordDisplay);
        }
        // 回车在 test2 下的逻辑已在 onEnterTest2 / onEnterTest2Stark 中处理
      }
    };

    // =============== 12. 暂停背诵功能 ===============
    const pauseRecite = () => {
      // 保存在后端的话，可以发一个“同步进度”的请求
      persistProgress();
      bootstrapTaskModalInstance && bootstrapTaskModalInstance.hide();
      alert("任务进度已保存，您可以稍后继续。");
      window.location.reload();
    };

    // =============== 13. 音效播放 ===============
    const playSound = (type) => {
      let audioSrc = "";
      if (type === 'correct') {
        audioSrc = correctSound;
      } else if (type === 'incorrect') {
        audioSrc = incorrectSound;
      }
      if (audioSrc) {
        const audio = new Audio(audioSrc);
        audio.play();
      }
    };

    // =============== 14. 显示等级标签 ===============
    const getLevelLabel = (level) => {
      const levelMap = {
        1: "A1",
        2: "A2",
        3: "B1",
        4: "B2",
        5: "C1",
        6: "C2",
        7: "德福考试词汇"
      };
      return `Level ${level} (${levelMap[level] || "未知等级"})`;
    };

    const getLevelLabelByType = (type) => {
      const typeMap = {
        '名词': "名词",
        '动词': "动词",
        '形容词': "形容词",
        '其他': "其他"
      };
      return typeMap[type] || "未知类型";
    };

    // 选项类名计算
    const optionClass = (option) => {
      if (!meaningFeedback.value) return '';
      const wordObj = getCurrentWord();
      const correctTranslation = wordObj.chinese || "";
      if (option === correctTranslation) {
        return 'border-success bg-success bg-opacity-25';
      }
      if (option === selectedOption.value && option !== correctTranslation) {
        return 'border-danger bg-danger bg-opacity-25 shake-animation';
      }
      return '';
    };

    // 计算背诵进度（示例）
    const progressPercentage = computed(() => {
      const total = selectedIsStark.value 
        ? starkVerbs.value.total_words 
        : levelsInfo.value.find(info => info.level === selectedLevel.value)?.total_words || 1;
      const left = selectedIsStark.value 
        ? starkVerbs.value.leftover_words 
        : levelsInfo.value.find(info => info.level === selectedLevel.value)?.leftover_words || 0;
      const recited = total - left;
      return (recited / total) * 100;
    });

    const recitedCount = computed(() => {
      const total = selectedIsStark.value 
        ? starkVerbs.value.total_words 
        : levelsInfo.value.find(info => info.level === selectedLevel.value)?.total_words || 0;
      const left = selectedIsStark.value 
        ? starkVerbs.value.leftover_words 
        : levelsInfo.value.find(info => info.level === selectedLevel.value)?.leftover_words || 0;
      return total - left;
    });

    // 复习进度（演示）
    const reviewProgressPercentage = computed(() => {
      const total = currentSessionType.value === 'scheduled_review' ? pendingReviewCount.value : studiedWordsCount.value;
      const left = total; 
      const recited = total - left; 
      return total > 0 ? (recited / total) * 100 : 0;
    });

    const reviewRecitedCount = computed(() => {
      const total = currentSessionType.value === 'scheduled_review' ? pendingReviewCount.value : studiedWordsCount.value;
      const left = total;
      return total - left;
    });

    // =============== onMounted 和 onBeforeUnmount ===============
    onMounted(async () => {
        const modalEl1 = startReciteModal.value;
        const modalEl2 = startReviewModal.value;
        const modalEl3 = reciteTaskModal.value;
        const modalEl4 = confirmCancelModal.value;
        if (modalEl1 && modalEl2 && modalEl3 && modalEl4) {
            import("bootstrap/dist/js/bootstrap.bundle.min.js").then(() => {
                const bootstrap = window.bootstrap;
                bootstrapStartReciteModalInstance = new bootstrap.Modal(modalEl1, {
                    backdrop: "static",
                });
                bootstrapStartReviewModalInstance = new bootstrap.Modal(modalEl2, {
                    backdrop: "static",
                });
                bootstrapTaskModalInstance = new bootstrap.Modal(modalEl3, {
                    backdrop: "static",
                });
                bootstrapConfirmCancelModalInstance =
                    new bootstrap.Modal(modalEl4, {
                        backdrop: "static",
                    });
            });
        }
        await fetchLevelsInfo();
        await fetchReviewStats();
        await restoreProgress();

        window.addEventListener("keydown", handleKeyDown);
    });



    onBeforeUnmount(() => {
      window.removeEventListener("keydown", handleKeyDown);
    });

    watch(
      [taskQueue, currentTaskIndex],
      () => {
        persistProgress();
      },
      { deep: true }
    );

    // 计算属性：根据 currentSessionType 判断显示的标题
    const currentSessionTypeLabel = computed(() => {
      if (currentSessionType.value === 'recitation') return '背诵任务';
      if (currentSessionType.value === 'scheduled_review') return '进度复习';
      if (currentSessionType.value === 'word_challenge') return '单词挑战';
      return '背诵/复习任务';
    });

    // =============== 返回给模板的属性和方法 ===============
    return {
      // refs
      startReciteModal,
      startReviewModal,
      reciteTaskModal,
      confirmCancelModal,
      fillBlankInputRef,

      // 数据
      levelsInfo,
      starkVerbs,
      reciteCount,
      maxReciteCount,

      reviewCount,
      maxReviewCount,

      selectedLevel,
      selectedIsStark,

      taskQueue,
      currentTaskIndex,
      currentTask,
      totalTasks,
      isCompleted,
      isCanceled,

      reciteRecords,

      // 方法
      openStartReciteModal,
      openStartReviewModal,
      startRecite,
      startReview,
      openReciteTaskModal,
      confirmCancelRecite,
      closeConfirmCancelModal,
      cancelRecite,
      pauseRecite,

      completeLearnTask,
      handleChooseOption,
      checkMeaningChoice,

      fillBlankInput,
      fillBlankFeedback,
      fillBlankFeedbackClass,
      checkFillBlank,

      fillBlankP2,
      fillBlankP2Feedback,
      fillBlankP2FeedbackClass,
      fillBlankPresent,
      fillBlankPresentFeedback,
      fillBlankPresentFeedbackClass,
      fillBlankPast,
      fillBlankPastFeedback,
      fillBlankPastFeedbackClass,
      checkFillBlankStark,

      onEnterTest2,
      onEnterTest2Stark,

      proceedToNextTask,
      playPronunciation,
      resetRecite,
      finallyresetRecite,

      // computed
      currentWord,
      currentTestOptions,
      optionKeys,
      genderMap,
      hasOngoingRecite,
      hasPendingReviews,

      // 交互禁用
      disableInteraction,

      // 其余工具
      getLevelLabel,
      getLevelLabelByType,
      optionClass,

      progressPercentage,
      recitedCount,
      reviewProgressPercentage,
      reviewRecitedCount,
      pendingReviewCount,
      studiedWordsCount,

      currentSessionTypeLabel,
    };
  },
};
</script>

<style scoped>
.immersive-bg {
  min-height: 100vh;
  padding-top: 70px;
  background: linear-gradient(130deg, #b2f7ef 0%, #5fbff9 100%);
  background-size: cover;
  position: relative;
  overflow: hidden;
  animation: subtleBackgroundMove 60s linear infinite;
}

@keyframes subtleBackgroundMove {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.bg-overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(255, 255, 255, 0.4);
  z-index: 2;
}

.z-3 {
  z-index: 3;
  position: relative;
}

.card-immersive {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 1rem;
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card-immersive:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.1);
}

.card-immersive .card-header {
  border-bottom: none;
  background: rgba(0, 123, 255, 0.8);
}

.level-card {
  background: rgba(0, 123, 255, 0.7);
  border-radius: 0.75rem;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  border: 1px solid transparent;
}

.level-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
}

.level-1 { background-color: #1e3a8a; }
.level-2 { background-color: #1e40af; }
.level-3 { background-color: #2563eb; }
.level-4 { background-color: #3b82f6; }
.level-5 { background-color: #60a5fa; }
.level-6 { background-color: #93c5fd; }
.level-7 { background-color: #ef4444; }

.frosted-glass {
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(15px);
  border-radius: 1rem;
}

.modal-super-lg {
  max-width: 95% !important;
}

.immersive-modal .modal-content {
  min-height: 80vh;
}

.display-3 {
  font-size: 3rem;
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}

.word-display-box {
  border-radius: 0.5rem;
  background: rgba(240, 248, 255, 0.9);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.option-card {
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
  border: 2px solid transparent;
  border-radius: 0.5rem;
  background-color: #ffffff;
}

.option-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  border-color: #ced4da;
}

.option-card.border-success {
  border-color: #198754;
  background-color: #d1e7dd;
}

.option-card.border-danger {
  border-color: #dc3545;
  background-color: #f8d7da;
}

.shake-animation {
  animation: shake 0.5s;
}

@keyframes shake {
  0% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  50% { transform: translateX(5px); }
  75% { transform: translateX(-5px); }
  100% { transform: translateX(0); }
}

.form-control-lg {
  padding: 1rem;
  font-size: 1.25rem;
  border-radius: 2rem;
  border: 1px solid #ced4da;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-control-lg:focus {
  border-color: #80bdff;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.btn-lg {
  padding: 0.75rem 1.5rem;
  font-size: 1.25rem;
  border-radius: 2rem;
}

.button-container-up {
  margin-top: -0.5rem; /* 向上移动 */
}

.btn-block {
  width: 100%;
}

.btn-outline-secondary {
  border-color: #0DCAF0;
  color: #25CFF1;
}

.btn-outline-secondary:hover {
  background-color: #6c757d;
  color: #ffffff;
}

.btn-outline-primary {
  border-color: #0d6efd;
  color: #0d6efd;
}

.btn-outline-primary:hover {
  background-color: #0d6efd;
  color: #ffffff;
}

.btn-info {
  background-color: #0dcaf0;
  border-color: #0dcaf0;
  color: #ffffff;
}

.btn-info:hover {
  background-color: #31d2f2;
  border-color: #31d2f2;
}

.btn-warning {
  background-color: #ffc107;
  border-color: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background-color: #ffca2c;
  border-color: #ffca2c;
}

.btn-danger {
  background-color: #dc3545;
  border-color: #dc3545;
  color: #ffffff;
}

.btn-danger:hover {
  background-color: #e63946;
  border-color: #e63946;
}

.btn-secondary {
  background-color: #6c757d;
  border-color: #6c757d;
  color: #ffffff;
}

.btn-secondary:hover {
  background-color: #5a6268;
  border-color: #545b62;
}

.immersive-input {
  background: rgba(255, 255, 255, 0.8);
  box-shadow: inset 0 0 5px rgba(0,0,0,0.1);
}

@media (max-width: 768px) {
  .display-3 {
    font-size: 2.5rem;
  }
}

.preview-box {
  max-height: 400px;
  overflow-y: auto;
}

.preview-box ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.preview-box li {
  padding: 0.5rem 1rem;
}

.progress {
  background-color: #e9ecef;
}

.progress-bar {
  transition: width 0.6s ease;
}

.intro-box {
  background-color: #f8f9fa;
  border-radius: 0.5rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.selection-section input {
  width: 100%;
}

.instructions-section ul li {
  margin-bottom: 0.5rem;
}

.instructions-section strong {
  color: #0d6efd;
}

.review-card {
  background: rgba(40, 167, 69, 0.7);
  border-radius: 0.75rem;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  border: 1px solid transparent;
}

.review-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
}

/* 新增：在禁用交互时给整个容器加一个类，阻止鼠标点击和键盘事件 */
.disable-overlay {
  pointer-events: none;
  opacity: 0.85;
}
</style>
